package com.opal.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(value = {"com.opal.**.mapper.sqlServercpd"}, sqlSessionTemplateRef  = "sqlServercpdSessionTemplate")
public class SqlServerDataSourceCPD {

    @Bean(name = "sqlservercpdDatasource")
    @ConfigurationProperties(prefix="spring.datasource.sqlservercpd")
    public DataSource createDataSource(){
        return DataSourceBuilder.create()
                .type(ComboPooledDataSource.class)
                .build();
    }

    @Bean(name = "sqlServercpdSessionFactory")
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("sqlservercpdDatasource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/opal/essence/mapper/sqlServer/*.xml"));//指定mapper.xml路径
        return bean.getObject();
    }

    @Bean(name = "sqlServercpdTransactionManager")
    public DataSourceTransactionManager mysqlTransactionManager(@Qualifier("sqlservercpdDatasource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlServercpdSessionTemplate")
    public SqlSessionTemplate mysqlSqlSessionTemplate(@Qualifier("sqlServercpdSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
